<script setup lang="ts">
defineOptions({
  name: "pay"
});
import { throttle, debounce } from "@pureadmin/utils";
import { onMounted, reactive, ref, watch, computed } from "vue";
import {
  getUserServer,
  getUserPackage,
  user_update_plan_info,
  user_update_vm_info,
  pay_request,
  getVirtualList
} from "@/api/user";
import { procedure_get_price, procedure_vir_price } from "@/api/pay";
import countryList from "@/utils/country";
import { message } from "@/utils/message";
import { getUserMirrorList } from "@/api/mirror";
import { mainUrl } from "@/api/utils";
import { useRouter } from "vue-router";
const router = useRouter();
onMounted(async () => {
  await VirtualList();
  let res = await getUserServer();
  res.data = res.data.map((item: any) => {
    if (countryList[item.location] != undefined) {
      return { ...item, ico: `/images/flag_${countryList[item.location]}.png` };
    } else {
      return { ...item, ico: `/images/flag_cn.png` };
    }
  });
  serverList.value = res.data;
  serverList.value = serverList.value.filter(item => item.hide == 0);
  getWidth();
});

const Type = ref("");
const ToBuy = async (data: any, tyep: any = "dockerContainer") => {
  Type.value = tyep;
  let res = await getUserPackage(data);
  plan_list.value = res.data;
  plan_list.value = plan_list.value.filter(item => item.number != 0);
  if (plan_list.value.length == 0) {
    message("暂无套餐，请选择其他服务器", { type: "error" });
  } else {
    plan_id.value = plan_list.value[0].plan_id;
    plan_data.value = plan_list.value[0];
    pagin.server_id = data;
    getUserMirrorList(pagin).then(res => {
      image_list.value = res.data.data;
      image_list.value = image_list.value.filter(item => item.state == 1);
      total.value = res.data.count;
    });
    dialogFormVisible.value = true;
    plan_data.value.pay_type = "3";
  }
};
//镜像分页
const pagin = reactive({
  server_id: "",
  page: 1,
  count: 12,
  key: ""
});
const search = () => {
  getUserMirrorList(pagin).then(res => {
    image_list.value = res.data.data;
    image_list.value = image_list.value.filter(item => item.state == 1);
    total.value = res.data.count;
  });
};
const total = ref();
const handleCurrentPageChange = async newPage => {
  pagin.page = newPage;
  getUserMirrorList(pagin).then(res => {
    image_list.value = res.data.data;
    image_list.value = image_list.value.filter(item => item.state == 1);
    total.value = res.data.count;
  });
};
const serverList = ref([]);
const loading = ref(false);
const dialogFormVisible = ref(false);
const plan_list = ref([
  {
    plan_id: "1",
    name: "基础套餐",
    memory: "100",
    disk: "200",
    cpu: "200",
    price: "18",
    bandwidth: "100",
    threshold_rx: "100",
    threshold_tx: "20",
    number: 38,
    description: "基础套餐，一般用于建站使用"
  }
]);
const plan_id = ref(plan_list.value[0].plan_id);
const plan_data = ref(plan_list.value[0]);
const additional_disk = ref(0);
const network_list = [
  {
    value: "nginx",
    name: "建站服务"
  },
  {
    value: "port_forward",
    name: "自定义端口"
  },
  {
    value: "floating_ip",
    name: "独立ip"
  }
];
// 容器数据
const get_pay_val = ref("0");
const prot_data = ref([]);
const image_id = ref("");
const image_list = ref([]);
const pay_months = ref(1);
// 虚拟机数据
const Get_vir_val = ref("0");
watch(
  [plan_data, additional_disk, prot_data, pay_months],
  () => {
    getpay(); //计算容器价格
    GetVirPay();
  },
  { deep: true }
);
// 容器订单提交
const submit = debounce(() => {
  loading.value = true;
  let env = envList.value.reduce((acc, cur) => {
    acc[cur.key] = cur.value;
    return acc;
  }, {});
  env = JSON.stringify(env);
  let objInfo = {
    server_id: plan_data.value.server_id,
    plan_id: plan_data.value.plan_id,
    volume_size: additional_disk.value,
    pay_months: pay_months.value,
    proxy: JSON.stringify(prot_data.value),
    pay_type: plan_data.value.pay_type,
    image_id: image_id.value,
    env: env
  };
  if (plan_data.value.pay_type == 3) {
    objInfo.pay_type = 0;
  }
  user_update_plan_info(objInfo).then(res => {
    loading.value = false;
    if (res.data.code == 200) {
      //生成订单
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        console.log("支付信息", res);
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
          dialogFormVisible.value = false;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          message("支付成功", { type: "success" });
          router.push(
            `/self/container?container_id=${res.data.data.trade_table_id}`
          );
        }
      });
    } else {
      message(res.data.msg, { type: "error" });
    }
  });
});
// 虚拟机订单提交
const virPaySubmit = debounce(() => {
  let objInfo = {
    plan_id: plan_data.value.plan_id,
    volume_size: additional_disk.value,
    pay_months: pay_months.value,
    pay_type: plan_data.value.pay_type,
    image_id: image_id.value
  };
  console.log("虚拟机提交参数", objInfo);
  user_update_vm_info(objInfo).then(res => {
    loading.value = false;
    if (res.data.code == 200) {
      //生成订单
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        console.log("支付信息", res);
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
          dialogFormVisible.value = false;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          message("支付成功", { type: "success" });
          router.push(
            `/self/vmContainer?container_id=${res.data.data.trade_table_id}`
          );
        }
      });
    } else {
      message(res.data.msg, { type: "error" });
    }
  });
});
// 容器价格计算接口
const getpay = debounce(() => {
  let objInfo = {
    server_id: plan_data.value.server_id,
    plan_id: plan_data.value.plan_id,
    volume_size: additional_disk.value,
    pay_months: pay_months.value,
    proxy: JSON.stringify(prot_data.value),
    image_id: image_id.value
  };
  if (prot_data.value.length != 0) {
    procedure_get_price(objInfo).then(res => {
      if (res.data.code == 200) {
        get_pay_val.value = res.data.data.price;
      }
    });
  }
});
// getpay();
// 虚拟机价格计算接口
const GetVirPay = async () => {
  let objInfo = {
    plan_id: plan_data.value.plan_id,
    volume_size: additional_disk.value,
    pay_months: pay_months.value
  };
  await procedure_vir_price(objInfo).then(res => {
    Get_vir_val.value = res.data.data.price;
  });
};
const netVisible = ref(false);
const form = reactive({
  type: "",
  container_id: "",
  server_port: "",
  container_port: "",
  domain: "",
  floating_ip: ""
});
// 容器结算金额显示
const formattedPayVal = computed(() => {
  return parseFloat(get_pay_val.value).toFixed(2);
});
// 虚拟机结算金额显示
const formattedVirPay = computed(() => {
  return parseFloat(Get_vir_val.value).toFixed(2);
});
const addnet = data => {
  if (data.type != "") {
    const entries = Object.entries(data);
    // 过滤掉属性值为空字符串的属性
    const filteredEntries = entries.filter(([key, value]) => value !== "");
    // 将过滤后的数组转换回对象
    const filteredObj = Object.fromEntries(filteredEntries);
    if (
      (prot_data.value.find(item => item.type != "floating_ip") &&
        data.type == "floating_ip" &&
        prot_data.value.length > 0) ||
      (prot_data.value.find(item => item.type == "floating_ip") &&
        data.type != "floating_ip" &&
        prot_data.value.length > 0)
    ) {
      message("独立ip不能与其他网络共存", { type: "error" });
      Object.keys(form).forEach(key => {
        form[key] = "";
      });
    } else {
      if (editPRO.value == false) {
        prot_data.value.push(filteredObj);
        message("添加成功！", { type: "success" });
      } else {
        prot_data.value[proIndex.value] = filteredObj;
        message("修改成功！", { type: "success" });
      }
      Object.keys(form).forEach(key => {
        form[key] = "";
      });
      netVisible.value = false;
    }
  } else {
    message("请填写完整", { type: "error" });
  }
};

watch(
  () => form.type,
  (newType, oldType) => {
    console.log("类型从", oldType, "变更为", newType);
    // 在此处添加根据类型变化清空表单项的逻辑
    if (oldType !== "" && newType !== oldType) {
      if (newType !== "port_forward" && newType !== "nginx") {
        form.container_port = ""; // 如果新类型不需要显示端口，则清空
      }
      if (newType !== "nginx") {
        form.domain = ""; // 如果新类型不需要域名，则清空
      }
    }
  },
  { deep: true }
);
const pay_url = ref("");
const pay_dialog = ref(false);
const pay_src = ref("");
const delProt = (index, data) => {
  prot_data.value.splice(index, 1);
};
//镜像
const changeImage = () => {
  console.log("选择了", image_id.value);
  let chooseplan;
  if (Type.value == "hyperV") {
    chooseplan = image_list.value.find(item => {
      return item.id == image_id.value;
    });
  } else {
    chooseplan = image_list.value.find(item => {
      return item.image_id == image_id.value;
    });
    if (chooseplan.plan_id != null) {
      plan_id.value = chooseplan.plan_id;
    }
    if (chooseplan.proxy == null) {
      prot_data.value = [];
    } else {
      prot_data.value = JSON.parse(chooseplan.proxy);
    }
    if (chooseplan.env == null) {
      envList.value = [];
    } else {
      let obj = JSON.parse(chooseplan.env);
      envList.value = Object.entries(obj).map(([key, value]) => ({
        key,
        value
      }));
    }
  }
  console.log("选择了", chooseplan);
};
//镜像变量
const envItem = reactive({
  key: "",
  value: ""
});
const envList = ref([]);
const envSwitch = ref(false);
const addenv = data => {
  if (data.key == "" || data.value == "") {
    message("请填写完整", { type: "error" });
    return;
  }
  if (editENV.value == false) {
    envList.value.push({ ...data });
    message("添加成功", { type: "success" });
  } else {
    envList.value[envIndex.value] = { ...data };
    message("修改成功", { type: "success" });
  }

  envSwitch.value = false;
  envItem.key = "";
  envItem.value = "";
};
const delenv = index => {
  envList.value.splice(index, 1);
  message("删除成功", { type: "success" });
};
const editENV = ref(false);
const envIndex = ref(0);
const editenv = (index, data) => {
  envSwitch.value = true;
  editENV.value = true;
  envIndex.value = index;
  envItem.key = data.key;
  envItem.value = data.value;
};
const editPRO = ref(false);
const proIndex = ref(0);
const editProt = (index, data) => {
  netVisible.value = true;
  editPRO.value = true;
  proIndex.value = index;
  Object.keys(form).forEach(key => {
    form[key] = data[key];
  });
};
//渲染卡片
const replace_html = (card, html) => {
  html = html.replace("card.ico", card.ico).replace("card.name", card.name);
  return html;
};
const isMobile = ref(false);
const getWidth = () => {
  if (window.innerWidth < 768) {
    isMobile.value = true;
  } else {
    isMobile.value = false;
  }
};
//提示
const tooltipVisible = ref(false);
const currentTooltip = ref("");
const showNumber = ref(null);
const showTooltip = (text, index) => {
  currentTooltip.value = text;
  tooltipVisible.value = true;
  showNumber.value = index;
};
const hideTooltip = () => {
  tooltipVisible.value = false;
};

// 获取虚拟机列表
const VirtualServerList = ref([]);
const VirtualList = async () => {
  let res = await getUserServer({ server_type: "hyperV" });
  res.data = res.data.map((item: any) => {
    if (countryList[item.location] != undefined) {
      return { ...item, ico: `/images/flag_${countryList[item.location]}.png` };
    } else {
      return { ...item, ico: `/images/flag_cn.png` };
    }
  });
  VirtualServerList.value = res.data;
  VirtualServerList.value = VirtualServerList.value.filter(
    item => item.hide == 0
  );
};
</script>

<template>
  <div>
    <div class="text-#000 text-20px font-bold m-l-10px">云容器:</div>
    <div class="pay_body">
      <el-card v-for="card in serverList" class="pay_card" shadow="hover">
        <div v-html="replace_html(card, card.html)" />
        <div style="text-align: center">
          <el-button class="button" @click="ToBuy(card.server_id)">点击购买</el-button>
        </div>
      </el-card>
    </div>
    <div class="text-#000 text-20px font-bold m-l-10px">云虚拟机:</div>
    <div class="pay_body">
      <el-card v-for="card in VirtualServerList" class="pay_card" shadow="hover">
        <div v-html="replace_html(card, card.html)" />
        <div style="text-align: center">
          <el-button class="button" @click="ToBuy(card.server_id, 'hyperV')">点击购买</el-button>
        </div>
      </el-card>
    </div>
    <el-dialog v-model="dialogFormVisible" top="5vh" :title="Type == 'hyperV' ? '创建虚拟机' : '创建容器'"
      :width="isMobile ? '90vw' : '1000px'">
      <el-form v-loading="loading" :width="isMobile ? '90vw' : '1000px'">
        <el-form-item label="选择镜像">
          <div>
            <div>
              <el-input v-model="pagin.key" placeholder="请输入镜像名称" style="width: 200px; margin-bottom: 10px"
                @blur="search" />
            </div>
            <el-radio-group v-model="image_id" @change="changeImage">
              <el-radio v-for="(image, index) in image_list" :value="Type == 'hyperV' ? image.id : image.image_id"
                size="large" border>
                <div class="image-preview" @mouseover="showTooltip(image.description, index)" @mouseout="hideTooltip">
                  <img :src="image.image_ico
                      ? mainUrl + image.image_ico
                      : '/images/logoo.jpg.jpg'
                    " />
                  <span>{{
                    image.show_name ? image.show_name : image.name
                    }}</span>
                </div>
                <div v-if="tooltipVisible && showNumber == index && currentTooltip" :key="index" class="tooltip">
                  {{ currentTooltip }}
                </div>
              </el-radio>
            </el-radio-group>
            <div style="margin-top: 20px">
              <el-pagination background layout="prev, pager, next" :total="total" :current-page="pagin.page"
                :page-size="pagin.count" @update:current-page="handleCurrentPageChange" />
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="Type == 'hyperV' ? '虚拟机套餐' : '容器规格'">
          <el-radio-group v-model="plan_id">
            <el-radio v-for="plan in plan_list" :value="plan.plan_id" border @click="plan_data = plan">{{ plan.name
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="font-weight: bold; margin-bottom: 10px">规格说明</div>
        <el-form-item>
          <el-descriptions :column="2" border size="large">
            <el-descriptions-item label="套餐名称" label-align="right" align="center">{{ plan_data.name
              }}</el-descriptions-item>
            <el-descriptions-item label="内存" label-align="right" align="center">{{ plan_data.memory }}
              MB</el-descriptions-item>
            <el-descriptions-item label="硬盘" label-align="right" align="center">
              {{ plan_data.disk }} GB
            </el-descriptions-item>
            <el-descriptions-item label="CPU" label-align="right" align="center">{{ plan_data.cpu }}{{ Type == "hyperV"
              ? "核" : "毫核" }}
            </el-descriptions-item>
            <el-descriptions-item v-if="Type == 'dockerContainer'" label="上行带宽" label-align="right" align="center">{{
              Math.floor(plan_data.bandwidth_tx)
            }}
              mbps</el-descriptions-item>
            <el-descriptions-item v-if="Type == 'dockerContainer'" label="下行带宽" label-align="right" align="center">{{
              Math.floor(plan_data.bandwidth_rx)
            }}
              mbps</el-descriptions-item>
            <el-descriptions-item v-if="Type == 'hyperV'" label="默认允许开放端口数" label-align="right" align="center">{{
              plan_data.port_num }}</el-descriptions-item>
            <el-descriptions-item v-if="Type == 'hyperV'" label="默认允许快照数" label-align="right" align="center">{{
              plan_data.snapshot_num }}
            </el-descriptions-item>
            <el-descriptions-item label="剩余数量" label-align="right" align="center">{{ plan_data.number
              }}</el-descriptions-item>
            <el-descriptions-item label="价格" label-align="right" align="center">{{ plan_data.price }}
              元</el-descriptions-item>
            <el-descriptions-item label="描述" label-align="right" align="center" span="2">{{ plan_data.description
              }}</el-descriptions-item>
          </el-descriptions>
        </el-form-item>
        <el-form-item :label="Type == 'hyperV' ? '额外数据卷:（GB）' : '额外容量:（GB）'">
          <el-slider v-if="isMobile == false" v-model="additional_disk" show-input show-tooltip max="1000" />
          <el-input v-if="isMobile == true" v-model="additional_disk" type="number" max="1000" />
        </el-form-item>
        <el-form-item label="购买时间:（月）">
          <el-slider v-if="isMobile == false" v-model="pay_months" show-input show-tooltip max="1000" />
          <el-input v-if="isMobile == true" v-model="pay_months" type="number" max="1000" />
        </el-form-item>
        <div v-if="Type != 'hyperV'" style="font-weight: bold; margin-bottom: 10px">
          网络类型选择
        </div>
        <el-form-item v-if="Type != 'hyperV'">
          <div style="display: flex; flex-wrap: wrap">
            <el-button @click="
              netVisible = true;
            editPRO = false;
            ">添加网络</el-button>
            <el-table class="table_el" :data="prot_data" :width="isMobile ? '40vw' : '100%'">
              <el-table-column label="网络类型">
                <template #default="scope">
                  {{
                    scope.row.type == "nginx"
                      ? "建站服务"
                      : scope.row.type == "floating_ip"
                        ? "独立ip"
                        : "自定义端口"
                  }}
                </template>
              </el-table-column>
              <el-table-column label="容器端口" prop="container_port" />
              <el-table-column label="域名" prop="domain" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="delProt(scope.$index, scope.row)">删除</el-button>
                  <el-button type="text" @click="editProt(scope.$index, scope.row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <div v-if="Type != 'hyperV'" style="font-weight: bold; margin-bottom: 10px">
          环境变量
        </div>
        <el-form-item v-if="Type != 'hyperV'">
          <div style="display: flex; flex-wrap: wrap">
            <el-button @click="
              envSwitch = true;
            editENV = false;
            ">添加环境变量</el-button>
            <el-table class="table_el" :data="envList" :width="isMobile ? '40vw' : '100%'">
              <el-table-column label="name值" prop="key" />
              <el-table-column label="value值" prop="value" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="delenv(scope.$index, scope.row)">删除</el-button>
                  <el-button type="text" @click="editenv(scope.$index, scope.row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="支付方式">
          <!-- <el-checkbox label="优先使用余额支付" checked disabled /> -->
          <el-radio v-model="plan_data.pay_type" label="3" border>余额</el-radio>
          <el-radio v-model="plan_data.pay_type" label="0" border>支付宝</el-radio>
          <el-radio v-model="plan_data.pay_type" label="1" border>微信</el-radio>
        </el-form-item>
        <el-form-item v-if="pay_src != ''" label="扫码支付">
          <el-image style="width: 100px; height: 100px" :src="pay_src" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="pay_money">
          <el-statistic v-if="Type != 'hyperV'" title="总计结算金额：" :value="formattedPayVal || '- -' + ' 元'" suffix="">
            <template #suffix>
              <el-icon style="vertical-align: -20px">
                <ChatLineRound />
              </el-icon>
            </template>
          </el-statistic>
          <el-statistic v-if="Type == 'hyperV'" title="总计结算金额：" :value="formattedVirPay || '- -' + ' 元'" suffix="">
            <template #suffix>
              <el-icon style="vertical-align: -20px">
                <ChatLineRound />
              </el-icon>
            </template>
          </el-statistic>
        </div>
        <div class="dialog-footer">
          <el-button @click="
            dialogFormVisible = false;
          prot_data = [];
          envList = [];
          pay_src = '';
          ">关闭</el-button>
          <el-button v-if="Type != 'hyperV'" type="primary" :disabled="prot_data.length != 0 &&
              image_id != '' &&
              plan_data.pay_type != null
              ? false
              : true
            " @click="submit()">
            提交订单
          </el-button>
          <el-button v-if="Type == 'hyperV'" type="primary" :disabled="image_id == '' || Get_vir_val <= '0'"
            @click="virPaySubmit()">
            提交订单
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="netVisible" title="网络信息" :width="isMobile ? '80vw' : '500px'" draggable overflow>
      <div>
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="网络类型">
            <el-select v-model="form.type" placeholder="请选择" style="width: 240px">
              <el-option v-for="item in network_list" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.type == 'port_forward' || form.type == 'nginx'" label="容器内部端口号" :rules="[
            {
              required: true,
              message: '请输入容器内部端口号',
              trigger: 'blur'
            }
          ]">
            <el-input v-model="form.container_port" type="number" :min="1" :max="65535" placeholder="端口号应在1-65535之间" />
          </el-form-item>
          <el-form-item v-if="form.type == 'nginx'" label="域名">
            <el-input v-model="form.domain" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="netVisible = false">关闭</el-button>
          <el-button type="primary" @click="addnet(form)"> 添加网络 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="envSwitch" title="环境变量" :width="isMobile ? '80vw' : '500px'" draggable overflow>
      <div>
        <el-form :model="envItem" label-width="auto" style="max-width: 600px">
          <el-form-item label="name值">
            <el-input v-model="envItem.key" />
          </el-form-item>
          <el-form-item label="value值">
            <el-input v-model="envItem.value" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="envSwitch = false">关闭</el-button>
          <el-button type="primary" @click="addenv(envItem)"> 添加</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="pay_dialog" title="支付" style="width: 90%; height: 1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100%; height: 800px" />
    </el-dialog>
  </div>
</template>

<style>
.pay_body {
  display: flex;
  flex-wrap: wrap;
  max-height: 600px;
  overflow-y: auto;
}

.pay_card {
  margin: 10px;
  width: 200px;
}

.image-preview {
  display: flex;
  align-items: center;
}

.image-preview img {
  width: 35px;
  height: 35px;
  margin-right: 10px;
}

.image-preview span {
  font-size: 14px;
}

.tooltip {
  position: absolute;
  background: #333;
  color: #fff;
  padding: 5px;
  border-radius: 5px;
  z-index: 100;
  font-size: 12px;
  max-width: 300px;
  min-width: 250px;
  white-space: wrap;
}
</style>
